import {AsyncStorage} from 'react-native'
import Trending from 'GitHubTrending'

export const FLAG_STORAGE = {
    flag_popular: 'popular',
    flag_trending: 'trending'
}


export default class DataStore {
    /**
     * 获取数据，优先获取本地数据，无本地数据或者本地数据过期则获取网络数据
     * @param url
     * @param flag //判断是Popular,还是Trending
     * @return {Promise}
     */
    fetchData(url, flag) {
        return new Promise((resolve, reject) => {
            this.fetchLocalData(url)
                .then(wrapData => {
                    if (wrapData && DataStore.checkTimestampValid(wrapData.timestamp)) {
                        resolve(wrapData)
                    } else {
                        this.fetchNetData(url, flag)
                            .then(data => {
                                resolve(this._wrapData(data))
                            })
                            .catch(error => {
                                reject(error)
                            })
                    }
                })
                .catch(error => {
                    this.fetchNetData(url, flag)
                        .then(data => {
                            resolve(this._wrapData(data))
                        })
                        .catch(error => {
                            reject(error)
                        })
                })
        })
    }

    /**
     * 获取网络数据
     * @param url
     * @param flag
     * @return {Promise<any> | Promise}
     */
    fetchNetData(url, flag) {
        return new Promise((resolve, reject) => {
            if (flag !== FLAG_STORAGE.flag_trending) {
                fetch(url)
                    .then(response => {
                        if (response.ok) {
                            return response.json()
                        }
                        throw new Error('Network response Error')
                    })
                    .then(responseData => {
                        this.saveData(url, responseData)
                        resolve(responseData)
                    })
                    .catch(error => {
                        reject(error)
                    })
            }else{
                new Trending().fetchTrending(url)
                    .then(items=>{
                        if(!items){
                            throw new Error('responseData is null')
                        }
                        this.saveData(url,items)
                        resolve(items)
                    })
                    .catch(error=>{
                        reject(error)
                    })
            }
        })
    }

    /**
     * 检查是否超过有效期4小时
     * @param timestamp
     * @return {boolean}
     */
    static checkTimestampValid(timestamp) {
        const currentDate = new Date()
        let targetDate = new Date()
        targetDate.setTime(timestamp)
        if (currentDate.getMonth() !== targetDate.getMonth()) return false
        if (currentDate.getDate() !== targetDate.getDate()) return false
        if (currentDate.getHours() - targetDate.getHours() > 4) return false //有效期为4个小时
        return true
    }

    /**
     * 保存数据到本地
     * @param url
     * @param data
     * @param callBack
     */
    saveData(url, data, callBack) {
        AsyncStorage.setItem(url, JSON.stringify(this._wrapData(data)), callBack)
    }

    _wrapData(data) {
        return {
            timestamp: new Date().getTime(),
            data,
        }
    }

    /**
     * 获取本地数据
     * @param url
     * @return {Promise<any> | Promise}
     */
    fetchLocalData(url) {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(url, (error, value) => {
                if (!error) {
                    try {
                        resolve(JSON.parse(value))
                    } catch (e) {
                        reject(e)
                        console.error(e)
                    }
                } else {
                    reject(error)
                    console.error(error)
                }

            });
        })
    }
}